import {Component, OnInit, AfterViewInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {EChartsOption} from 'echarts';
import {EchartOptions} from './echart-option';
import {OverviewServices} from '../../http/services';

@Component({
  selector: 'app-overview-left',
  templateUrl: './left.component.html',
  styleUrls: ['./left.component.less']
})
export class LeftComponent implements OnInit, AfterViewInit {
  chartOption1!: EChartsOption;
  chartOption2!: EChartsOption;
  chartObject2: any;
  faultRateType = 'Y';
  runDays: number;
  isVisible = false;
  colorArray = [];
  rate = null;
  second;


  validateForm!: FormGroup;

  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    this.validateForm.reset();
    if (this.validateForm.valid) {
      console.log(this.validateForm.value);
    }
  }

  handleCloseOrCancel(): void {
    this.validateForm.reset();
    this.isVisible = false;

  }

  constructor(private http: OverviewServices, private fb: FormBuilder, private ecops: EchartOptions) {
  }

  loadFaultRate(): void {
    this.http.getDeviceFaultRate(this.faultRateType).subscribe(
      (response) => {
        const seriesArray = [];
        const legendName = [];
        if (response.code === 0) {
          for (const op of response.data) {
            seriesArray.push({
              type: 'bar',
              data: [op.rate.replace(/%/, '')],
              name: op.deviceTypeName,
              label: {
                show: true,
                position: 'top',
                formatter: (params) => params.value + '%'
              }
            });
            legendName.push(op.deviceTypeName);
          }
          const chartOption = this.ecops.faultOption;
          chartOption.series = seriesArray;
          chartOption.legend = {
            show: true,
            type: 'plain',
            data: legendName,
            bottom: 0,
            width: '80%',
            textStyle: {
              color: '#fff'
            }
          };
          this.chartOption2 = chartOption;
          if (this.chartObject2) {
            this.chartObject2.clear();
            this.chartObject2.setOption(this.chartOption2);
          }
        }
      }
    );
  }


  ngOnInit(): void {

    this.validateForm = this.fb.group({
      month: [null, [Validators.required]],
      zhubian: [null, [Validators.required]]
    });

    this.runDays = 66;
    this.chartOption1 = this.ecops.transformerOption;
  }

  ngAfterViewInit(): void {
    this.loadFaultRate();
  }

  onQuery(): void {
    this.rate = Math.floor(Math.random() * 100);
    this.second = Math.floor(Math.random() * 100 + 70);
  }
}
